<?php
/**
 * redis 应用小工具
 * User: znz
 * Date: 16-10-12
 */
class Func_Redisfunc{
	
    private $prefix = 'redis_public_key_';
    private static $obj = null;
    
    public static function getInstance() {
		if (empty ( self::$obj )) {
			self::$obj = new Func_Redisfunc();
		}
		return self::$obj;
	}
    /**
     * 每日登录验证
     * @param unknown $tag
     * @param unknown $uid
     * @return boolean
     */
    public function checkLogin($tag, $uid){
        if(!$uid){
        	return false;
        }
        $date_time = date('Ymd');
    	$tags = $this->prefix . $tag . '_' . $date_time;
    	$is_not = Lib_Redis_Hash::hGet($tags, $uid);
    	if($is_not){
    		return false;
    	}
    	Lib_Redis_Hash::hSet($tags, $uid, 1);
    	Lib_Redis_Hash::expireAt($tags, strtotime(date('Y-m-d').' 23:59:59'));
    	return true;
    }
    /**
     * 每日数量上限验证
     * @param unknown $tag
     * @param unknown $uid
     */
    public function checkceiling($tag, $uid, $num, $action = 'set'){
        if(!$uid or !$num){
        	return false;
        }
        $date_time = date('Ymd');
        $tags = $this->prefix . $tag . '_' . $date_time;
        if($action == 'get'){
            return Lib_Redis_Hash::hGet($tags, $uid);
        }
        $res_num = Lib_Redis_Hash::hIncrby($tags, $uid, 1);
        if($res_num > $num){
        	return false;
        }
        Lib_Redis_Hash::expireAt($tags, strtotime(date('Y-m-d').' 23:59:59'));
        return $res_num;
    }
    /**
     * 并发限制
     * @param unknown $tag
     * @param unknown $uid
     * @return boolean
     */
    public function checkconcurrent($tag, $uid){
    	if(!$uid){
    		return false;
    	}
    	$tags = $this->prefix . $tag . '_' . $uid;
    	$string_obj = new Lib_Redis_String();
 		$state = $string_obj->incr($tags);
 		if($state >= 5 and $state <= 10){
 			$string_obj::expireAt($tags, time() + 3600);
 		}
 		if($state == 1){
 			$string_obj::expireAt($tags, time() + 1);
 		}
    	return $state > 1 ? false : true;
    }
    /**
     * 快捷数据验证存储（可设置过期时间 单位：秒）
     * @param unknown $tag
     * @param unknown $uid
     * @param unknown $num
     * @param string $expire 秒
     * @return boolean
     */
    public function checkstorage($tag, $uid, $num, $expire = null){
    	if(!$uid){
    		return false;
    	}
    	$tags = $this->prefix . $tag . '_' . $uid;
    	$string_obj = new Lib_Redis_String();
    	$res_num = $string_obj->get($tags);
    	if($res_num >= $num){
    		return false;
    	}
    	$string_obj->incr($tags);
    	if($expire){
    		$string_obj::expireAt($tags, time() + $expire);
    	}
    	return true;
    }
}